package org.company.earth.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyExecutor implements Runnable {
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//MyExecutor.startExecService();
		//MyExecutor.startExecCallable();
		MyExecutor.startExecCallableCompletion();
	}
	
	public static void startExecService() {
		ExecutorService pool = Executors.newFixedThreadPool(3);
		for(int i = 0 ; i < 10 ; i++) {
			pool.execute(new MyExecutor());
		}
		pool.shutdown();
	}
	
	public static void startExecCallable() throws InterruptedException, ExecutionException {
		ExecutorService pool = Executors.newFixedThreadPool(3);
		Future<Long> result = null;
		for(int i = 0 ; i < 10 ; i++) {
			result = pool.submit(new Callable<Long>() {
				public Long call() throws Exception {
					System.out.println("Executors:" + Thread.currentThread().getId());
					return Thread.currentThread().getId();
				}
			});
			System.out.println(result.get());
		}
	}
	
	public static void startExecCallableCompletion() throws InterruptedException, ExecutionException {
		ExecutorService pool = Executors.newFixedThreadPool(3);
		CompletionService<Long> completionpool = new ExecutorCompletionService<Long>(pool);
		Future<Long> result = null;
		for(int i = 0 ; i < 10 ; i++) {
			completionpool.submit(new Callable<Long>() {
				public Long call() throws Exception {
					System.out.println("Executors:" + Thread.currentThread().getId());
					return Thread.currentThread().getId();
				}
			});
		}
		
		for(int i = 0 ; i < 10 ; i++) {
			result = completionpool.take();
			System.out.println("CompletionResult is " + result.get());
		}
		pool.shutdown();
	}
	
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("Executors:" + Thread.currentThread().getId());
		try {
			Thread.sleep(1000*2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
